package com.common.service;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @classDescription:配置logback日志
 * @author:xiayingjie
 * @createTime:16/7/19
 */
@Component
public class InitializationService implements ApplicationListener<ContextRefreshedEvent> {


    @Value("#{'${log.dir}'.endsWith('/')?'${log.dir}':'${log.dir}'+'/'}")
    private String logDir;

    @Value("${log.name}")
    private String logName;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            configureLogback();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void configureLogback() throws IOException {

        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        try {
            JoranConfigurator jc = new JoranConfigurator();
            jc.setContext(context);
            context.reset();

            context.putProperty("LOG_DIR", logDir);
            context.putProperty("LOG_NAME", logName);

            jc.doConfigure(new ClassPathResource("logback.xml").getInputStream());
        } catch (JoranException je) {
            // StatusPrinter will handle this
            je.printStackTrace();
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(context);

    }
}

